package com.chaos.system.biz;


import com.chaos.framework.model.dto.result.data.DataResult;
import com.chaos.framework.starter.base.BaseController;
import com.chaos.system.api.dto.CosCredentialsDto;
import com.chaos.system.service.third.cos.CosFileProperties;
import com.chaos.system.service.third.cos.CosStsClient;
import com.tencent.cloud.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;

import java.io.IOException;
import java.util.TreeMap;

@Slf4j
@RestController
@Api(tags = "cos文件处理")
@RequestMapping("/cos")
public class CosController extends BaseController {


    @Resource
    private CosFileProperties cosFileProperties;

    @PostMapping("/getCredential")
    @ApiOperation(value = "", httpMethod = "POST")
    public DataResult getCredential() throws IOException {

        TreeMap<String, Object> config = new TreeMap<String, Object>();

        config.put("secretId", cosFileProperties.getSecretId());
        config.put("secretKey", cosFileProperties.getSecretKey());

        config.put("bucket", cosFileProperties.getBucket());
        config.put("region", cosFileProperties.getRegion());

        config.put("allowPrefixes", new String[]{"*"});

        String[] allowActions = new String[]{
                "cos:PutObject",
                // 表单上传、小程序上传
                "cos:PostObject",
                // 分块上传
                "cos:InitiateMultipartUpload",
                "cos:ListMultipartUploads",
                "cos:ListParts",
                "cos:UploadPart",
                "cos:CompleteMultipartUpload",
                "cos:GetObject",
                // 处理相关接口一般为数据万象产品 权限中以ci开头
                // 创建媒体处理任务
                "ci:CreateMediaJobs",
                // 文件压缩
                "ci:CreateFileProcessJobs"
        };

        config.put("allowActions", allowActions);

        Response response = CosStsClient.getCredential(config);
        CosCredentialsDto result = new CosCredentialsDto();

        result.setTmpSecretId(response.credentials.tmpSecretId);
        result.setTmpSecretKey(response.credentials.tmpSecretKey);
        result.setSessionToken(response.credentials.sessionToken);
        result.setStartTime(response.startTime);
        result.setExpiredTime(response.expiredTime);

        return dataResult(result);

    }

    @PostMapping("/getBucket")
    @ApiOperation(value = "", httpMethod = "POST")
    public DataResult getBucket() throws IOException {
        CosCredentialsDto result = new CosCredentialsDto();
        result.setBucket(cosFileProperties.getBucket());
        result.setRegion(cosFileProperties.getRegion());
        return dataResult(result);

    }


}

